package com.openlogic.common.core.utils.thread;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: Threads
 * @Description: 线程工具类
 * @author weiyongpeng
 * @date 2025年1月30日 上午9:16:56
 */
public class Threads {

	private static final Logger Logger = LoggerFactory.getLogger(Threads.class);

	public static void sleep(Long millisecondsSleeps) {
		try {
			Thread.sleep(millisecondsSleeps);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void shutdownAndAwaitTermination(ExecutorService pool) {
		if (pool != null && !pool.isShutdown()) {
			pool.shutdown();
			try {
				if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
					pool.shutdownNow();
					if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
						Logger.info("Pool dis not terminate!!");
					}
				}
			} catch (Exception e) {
				pool.shutdownNow();
				Thread.currentThread().interrupt();
			}
		}
	}

	public static void printException(Runnable run, Throwable t) {
		if (t == null && run instanceof Future<?>) {
			try {
				Future<?> future = (Future<?>) run;
				if (future.isDone()) {
					future.get();
				}
			} catch (CancellationException e) {
				t = e;
			} catch (ExecutionException e) {
				t = e.getCause();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
		}
		if (t != null) {
			Logger.info(t.getMessage(), t);
		}
	}

}
